package com.ly.mpayment.rest.up.jieyinlian;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;
import org.mortbay.util.MultiMap;
import org.mortbay.util.UrlEncoded;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.net.URLDecoder;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

@Component
@Path("jieyinlian")
public class JieYinLianRest {

	Logger logger = Logger.getLogger(JieYinLianRest.class);

	@Autowired
	IUporderService upOrderService;

	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	IDownShopInfoService shopService;

	@Autowired
	IUpShopInfoService upShopInfoService;

	/**
	 * @return
	 */
	@Path("callBack")
	@POST
	public synchronized String callBack(@RequestBody String body){
		logger.info("jieyinlian:"+body);
		MultiMap multimap = parceString(body);
		if(!StringUtils.isBlank(body)){
			UpOrder order = upOrderService.findById(multimap.getString("orderid"));
			if (order != null && multimap.getString("status").equals("1") && order.getStatus() == Config.status[0]) {
				order.setRemark(multimap.containsKey("status") ? multimap.getString("status") : URLDecoder.decode(multimap.getString("errormsg")));
				RechargeRest.successUpOrder.add(order);
				return "0000";
			}else if(order != null && order.getStatus() == Config.status[0] && multimap.getString("status").equals("2")){
				order.setRemark(multimap.containsKey("errormsg") ? URLDecoder.decode(multimap.getString("errormsg")) :  multimap.getString("status"));
				RechargeRest.failtUpOrder.add(order);
				JSONObject data = new JSONObject();
				return "0000";
			}else{
				logger.info("jieyinlian_not_found_order:" + body +","+ (order == null ? " order is null" : order.getUpphonenum() ));
			}
		}
		return "0000";
	}

	private MultiMap parceString(String str){
		MultiMap map = new MultiMap();
		UrlEncoded.decodeTo(str, map, "utf-8");
		return map;
	}

	/**
	 * @return
	 */
	public void commitOrder(UpOrder order, UpShopInfo shop) {
		UpOrder product = this.upOrderService.findOrderProduct(order.getUporderuuid());
		if (product != null) {
			JSONObject data = new JSONObject();
			data.put("version","V1.0");
			data.put("dealerid",shop.getAppId());
			data.put("orderid",order.getUporderuuid());
			String [] packages = order.getUpShopPro().getProductCode().split("\\|");
			data.put("chargetype",packages[0]);
			data.put("packagetype",packages[1]);
			data.put("photonum",order.getUpphonenum());
			data.put("flowsize",order.getUpShopPro().getUpfacevalue());
			data.put("ordertime",new DateUtils().toTimeStamp());
			data.put("callback",shop.getOrderCallAddress());
			data.put("mark","");

			data.put("sign",MD5.md5(StringSort.doSign(data)+shop.getUpkey()));
			String res = HttpClient.postUrl(shop.getOrderCommitAddress(),StringSort.jsonToString(data));
			logger.info("commitjieyinlian_result:" + data +",phone:"+order.getUpphonenum()+",res:"+res);
			if (!StringUtils.isBlank(res)) {
				net.sf.json.JSONObject json = JsonUtils.getJSONOBJCT();
				try {
					if (!StringUtils.isBlank(res)) {
						JsonUtils.iterateNodes(DocumentHelper.parseText(res).getRootElement(), json);
						net.sf.json.JSONObject result = json.getJSONObject("root");
						//{"root":{"orderid":"123456789","serialid":"987654321","resultno":"0000","orderamount":"98.76","balance":"33043.65","errormsg":"SUCCESS","mark":"",
						// "sign":"192ae0099f46de1d71228a5fa00c2d2e"}}
						if(result.containsKey("resultno") && result.getString("resultno").equals("0000")){
							upOrderService.updateUpOrderMsg(order, result.getString("serialid"),URLDecoder.decode(result.getString("errormsg")));
						}else if (result.containsKey("resultno") && codesError.contains(result.getString("resultno"))) {
							order.setRemark(result.containsKey("errormsg") ? URLDecoder.decode(result.getString("errormsg")) : Config.orderFailA);
							RechargeRest.failtUpOrder.add(order);
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}
			} else {
				upOrderService.commitFailt(order,  Config.commitFailt);
				logger.info("commitjieyinlian_error" + order.getUpphonenum());
			}
		}
	}

	/**
	 * 提单错误直接失败
	 */
	private static Set<String> codesError = new HashSet<String>(){{
		add("0001");
		add("0004");
		add("0005");
		add("0006");
		add("0007");
		add("0008");
		add("0009");
		add("0010");
		add("0011");
		add("0012");
		add("0013");
		add("0014");
		add("0015");
		add("0019");
		add("0022");
		add("0024");
		add("0025");
	}};


	/**
	 */
	public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
		if(upOrder != null ){
			UpOrder product = upOrderService.findOrderProduct(upOrder.getUporderuuid());
			if (product != null) {
				JSONObject data = new JSONObject();
				data.put("dealerid",shopInfo.getAppId());
				data.put("orderid",upOrder.getUporderuuid());
				data.put("sign",MD5.md5(StringSort.doSign(data)+shopInfo.getUpkey()));
				String res = HttpClient.postUrl(shopInfo.getOrderStatusAddress(),StringSort.jsonToString(data));
				logger.info("queryjieyinlian:"+res+"data:"+data+",phone:"+upOrder.getUpphonenum());
				if(res != null){
					net.sf.json.JSONObject json = JsonUtils.getJSONOBJCT();
					try {
						if (!StringUtils.isBlank(res)) {
							JsonUtils.iterateNodes(DocumentHelper.parseText(res).getRootElement(), json);
							net.sf.json.JSONObject result = json.getJSONObject("response");
							if(result.containsKey("resultno") && result.getString("resultno").equals("0000")){
								if( result.getString("status").equals("1") ){
									UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
									if(order != null && order != null && order.getStatus() == Config.status[0]){
										order.setRemark(result.containsKey("status") ? result.getString("status") : result.getString("status"));
										RechargeRest.successUpOrder.add(order);
									}
								}else if(result.getString("status").equals("2") ){
									UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
									if( order != null && order.getStatus() == Config.status[0]){
										order.setRemark(result.containsKey("errormsg") ? URLDecoder.decode(result.getString("errormsg")) : Config.orderFailA);
										RechargeRest.failtUpOrder.add(order);
									}
								}
							}else{
								logger.debug("queryjieyinlian查询失败:"+upOrder.getUpphonenum());
							}
						}
					}catch (Exception e){
						e.printStackTrace();
					}

				}else{
					logger.info("queryjieyinlian order failt:"+upOrder.getUpphonenum());
				}
			}
		}else{
			logger.info("queryjieyinlian order failt:"+upOrder.getUpphonenum());
		}
	}
}
